package clog

import (
	"compress/gzip"
	"encoding/json"
	"fmt"
	"likeadmin/constparam"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"
)

var WikiMap = sync.Map{}

var chPrintln = make(chan string, 10000)
var chFile = make(chan string, 10000)
var path = "./logs/"

func getFilename() string {
	path = "./logs/"
	var nowTime = time.Now()
	return path + "sxadmin" + fillZero(nowTime.Year()) + fillZero(int(nowTime.Month())) + fillZero(nowTime.Day()) +
		fillZero(nowTime.Hour()) + fillZero(nowTime.Minute()) + fillZero(nowTime.Second()) + ".log"
}

func fillZero(input int) string {
	if input < 10 {
		return "0" + strconv.Itoa(input)
	} else {
		return strconv.Itoa(input)
	}
}

func Println() {
	Init()
	for {
		var logString = <-chPrintln
		fmt.Println(logString)
	}
}

func PrintFile() {
	for {
		var logString = <-chFile
		fmt.Fprintf(writerLog, "%s", logString)
	}
}

var fileName = getFilename()
var writerLog, _ = os.Create(fileName)

func Init() {
	fileName = getFilename()

	writerLog, _ = os.Create(fileName)
}

func Info(info string, object interface{}) {
	var timeVar = time.Now()
	jsonStr, error := json.MarshalIndent(object, "", " ")
	if error != nil {
		return
	}
	var logString strings.Builder
	logString.WriteString("[")
	logString.WriteString(timeVar.Format("2006-01-02 15:04:05.000000000"))
	logString.WriteString("]")
	logString.WriteString("【")
	logString.WriteString(constparam.VERSION)
	logString.WriteString("】===")
	logString.WriteString(info)
	logString.WriteString(string(jsonStr))
	chPrintln <- logString.String()
	logString.WriteString("\r\n")
	chFile <- logString.String()

}

func Print(info string, input string) {
	var timeVar = time.Now()
	var logString strings.Builder
	logString.WriteString("[")
	logString.WriteString(timeVar.Format("2006-01-02 15:04:05.000000000"))
	logString.WriteString("]")
	/*	logString.WriteString("【")
		logString.WriteString(strconv.FormatInt(timeVar.UnixMilli(), 10))
		logString.WriteString("】")
		logString.WriteString("【")
		logString.WriteString(strconv.FormatInt(timeVar.UnixNano(), 10))
		logString.WriteString("】")*/
	logString.WriteString("【")
	logString.WriteString(constparam.VERSION)
	logString.WriteString("】===")
	logString.WriteString(info)
	logString.WriteString(input)
	chPrintln <- logString.String()
	logString.WriteString("\r\n")
	chFile <- logString.String()

}

func Split() {
	for {
		time.Sleep(20000000000 * 3 * 60)
		outputFile, _ := os.Create(fileName + ".gz")
		gzipWriter := gzip.NewWriter(outputFile) //gzipWriter:需要操作的句柄
		var readLogTmp, err = os.Open(fileName)
		if err != nil {
			continue
		}

		b := make([]byte, 1024)
		for {
			n, error := readLogTmp.Read(b)
			if error != nil {
				break
			}
			gzipWriter.Write(b[0:n])
		}
		readLogTmp.Close()
		gzipWriter.Close()
		writerLog.Close()
		os.Remove(fileName)
		fileName = getFilename()
		writerLog, _ = os.Create(fileName)

	}
}
